package be.groept.ace.enquete.filters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import be.groept.ace.enquete.model.beans.User;

public class SessionTrackingFilter implements Filter {
	private static Logger logger = Logger.getLogger(SessionTrackingFilter.class);
	private ArrayList<String> urlList;
	
	public void init(FilterConfig fConfig) throws ServletException {
		String urls = fConfig.getInitParameter("avoid-urls");
		StringTokenizer token = new StringTokenizer(urls, ",");
		urlList = new ArrayList<String>();
		while (token.hasMoreTokens()) {
			urlList.add(token.nextToken());
		}
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		//check if there is already a session going on -> if not create one
		HttpSession session = httpRequest.getSession(true);

		//get the user -> if no user logged in, this returns null
		User user = (User)session.getAttribute("user");
		
		//get the url of the request 
		String url = httpRequest.getServletPath();
		
		//check if it's an url to avoid
		boolean allowedRequest = urlList.contains(url);
		logger.debug(String.format("url %s is %sallowed without login", url, allowedRequest ? "" : "not " ));
		
		if(!allowedRequest) {

			if ( user == null) {
				//insert the requested path in the session, so we can redirect to it when the user logged in
				String requestedUrl = String.format("%s%s%s%s%s", 
														httpRequest.getContextPath(),
														httpRequest.getServletPath(), 
														httpRequest.getPathInfo() != null ? httpRequest.getPathInfo() : "",
														httpRequest.getQueryString() != null ? "?": "",
														httpRequest.getQueryString() != null ? httpRequest.getQueryString() : "");
				session.setAttribute("requestedUrl", requestedUrl);
				logger.debug(String.format("requested url: %s", requestedUrl));
				logger.debug("No user logged in: redirecting to login page...");
				httpResponse.sendRedirect("login");
				return;
			} else {
				logger.debug(String.format("allowed to continue for user: %s", user.toString()));
			}
		}
		
		chain.doFilter(request, response);
	}
	
	public void destroy() {
		urlList = null;
	}
	

}
